package com.example.movie.ui.user.order

import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.movie.R
import com.example.movie.common.constants.Constants
import com.example.movie.common.enums.LoadingSate
import com.example.movie.data.user.factory.UserViewModelFactory
import com.example.movie.data.user.model.OrderViewModel
import com.example.movie.data.user.model.vo.OrderVo
import com.example.movie.ui.user.adapter.OrderAdapter
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog
import kotlinx.android.synthetic.main.layout_order_list.*
import java.util.concurrent.TimeUnit

class OrderPlaceHolderFragment : Fragment() {

    private val orderViewModel: OrderViewModel by viewModels(ownerProducer = {requireActivity()}, factoryProducer = { UserViewModelFactory() })

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        setOrderObserver()
        return inflater.inflate(R.layout.layout_order_list, container, false)
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun setOrderObserver() {
        arguments?.getInt(ARG_SECTION_NUMBER).let { it ->
            it?.apply {
                when (this) {
                    Constants.OrderTab.NOT_GET -> {
                        orderViewModel.getNewOrder()
                        var newOrderAdapter: OrderAdapter? = null
                        orderViewModel.newOrders.observe(viewLifecycleOwner, {
                            with(it.success) {
                                this?.let {
                                    orders.apply {
                                        this.layoutManager =
                                            LinearLayoutManager(
                                                context,
                                                LinearLayoutManager.VERTICAL,
                                                false
                                            )
                                        newOrderAdapter = OrderAdapter(it as MutableList<OrderVo>)
                                        this.adapter = newOrderAdapter
                                        newOrderAdapter!!.notifyDataSetChanged()
                                    }
                                }
                            }
                        })

                        val loadingTipDialog = QMUITipDialog.Builder(requireContext())
                            .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                            .setTipWord("正在取票..")
                            .create()

                        orderViewModel.loadingSate.observe(viewLifecycleOwner, {
                            it?.let {
                                when (it.state) {
                                    LoadingSate.STOP -> {
                                    }
                                    LoadingSate.LOADING -> {
                                        if (!loadingTipDialog.isShowing) {
                                            loadingTipDialog.show()
                                        }
                                    }
                                    LoadingSate.SUCCESS -> {
                                        Log.e("fragmentHolder", "setOrderObserver: ${this@OrderPlaceHolderFragment}")
                                        loadingTipDialog.dismiss()
                                        val successTipDialog = QMUITipDialog.Builder(requireContext())
                                            .setIconType(QMUITipDialog.Builder.ICON_TYPE_SUCCESS)
                                            .setTipWord("取票完成")
                                            .create()
                                        successTipDialog.show()
                                        Handler(Looper.myLooper()!!).postDelayed({
                                            successTipDialog.dismiss()
                                        }, TimeUnit.SECONDS.toMillis(2))

                                        newOrderAdapter?.removeSuccessOrder(orderId = it.orderId)
                                        //loadingSate重新置为null
                                        orderViewModel.loadingSate.value = null
                                    }
                                }
                            }
                        })

                    }
                    Constants.OrderTab.SUCCESS -> {
                        orderViewModel.getSuccessOrder()
                        orderViewModel.successOrders.observe(viewLifecycleOwner, {
                            with(it.success) {
                                this?.let {
                                    orders.layoutManager =
                                        LinearLayoutManager(
                                            context,
                                            LinearLayoutManager.VERTICAL,
                                            false
                                        )
                                    val orderAdapter = OrderAdapter(this as MutableList<OrderVo>)
                                    orders.adapter = orderAdapter
                                    orderAdapter.notifyDataSetChanged()
                                }
                            }
                        })

                    }
                    Constants.OrderTab.EXPIRE -> {
                        orderViewModel.getExpireOrder()
                        orderViewModel.expireOrders.observe(viewLifecycleOwner, {
                            with(it.success) {
                                this?.let {
                                    orders.layoutManager =
                                        LinearLayoutManager(
                                            context,
                                            LinearLayoutManager.VERTICAL,
                                            false
                                        )
                                    val orderAdapter = OrderAdapter(this as MutableList<OrderVo>)
                                    orders.adapter = orderAdapter
                                    orderAdapter.notifyDataSetChanged()
                                }
                            }
                        })

                    }
                    else -> {
                    }
                }
            }
        }

    }

    companion object {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private const val ARG_SECTION_NUMBER = "section_number"

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        @JvmStatic
        fun newInstance(sectionNumber: Int): OrderPlaceHolderFragment {
            return OrderPlaceHolderFragment().apply {
                arguments = Bundle().apply {
                    putInt(ARG_SECTION_NUMBER, sectionNumber)
                }
            }
        }
    }


}